package services;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

public class Utils {

	public static String toQueryString(Map<String, String> data) {
		StringBuffer queryString = new StringBuffer();
		
		try {
			for (Entry<String, String> pair : data.entrySet()) {
				queryString.append(URLEncoder.encode(pair.getKey(), "UTF-8") + "=");
				queryString.append(URLEncoder.encode(pair.getValue(), "UTF-8") + "&");
			}
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}

		if (queryString.length () > 0) queryString.deleteCharAt(queryString.length () - 1);
		return queryString.toString();
	}

	public static HttpURLConnection getPostConnection(URL url, String params) throws IOException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setInstanceFollowRedirects(false); 
		connection.setRequestMethod("POST"); 
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
		connection.setRequestProperty("charset", "utf-8");
		connection.setFixedLengthStreamingMode(params.getBytes().length);
		connection.setUseCaches (false);
		
		DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
		wr.writeBytes(params);
		wr.flush();
		wr.close();
		
		return connection;
	}
	
	public static String getHashString(byte[] hash) {
		StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
	}
}
